package org.example;

import java.util.*;
/**
 * @Description 借助原型模式，拓展带有管理器的原型模式进行正方形和原型的面积计算
 *              就是在初始化的时候就在管理器中存了需要的模型，在使用的时候从管理器中找到对应的模型进行clone创建对象而不是重新new对象
 *              uml图见本目录下ProtoTypeShape.gif
 *                  shape接口继承Cloneable
 *                  实现类Square和Circle分别实现clone方法和面积计算方法(此处根据迪米特法则，应该使用抽象类将clone方法实现而不是到具体实现类在实现)
 *                  ProtoTypeManager作为管理器初始化时将两个实现类通过new的方式都存入到map结构中
 *                  ProtoTypeShape访问类通过管理器对实现类进行clone的方式提供出具体对象供访问类使用是
 *
 * @Date 9:53 2022/7/27
 * @Author sunye
 **/
interface Shape extends Cloneable {
    public Object clone();    //拷贝

    public void countArea();    //计算面积
}

class Circle implements Shape {
    @Override
    public Object clone() {
        Circle w = null;
        try {   
            w = (Circle) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("拷贝圆失败!");
        }
        return w;
    }

    public void countArea() {
        int r = 0;
        System.out.print("这是一个圆，请输入圆的半径：");
        Scanner input = new Scanner(System.in);
        r = input.nextInt();
        System.out.println("该圆的面积=" + 3.1415 * r * r + "\n");
    }
}

class Square implements Shape {
    @Override
    public Object clone() {
        Square b = null;
        try {
            b = (Square) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("拷贝正方形失败!");
        }
        return b;
    }

    public void countArea() {
        int a = 0;
        System.out.print("这是一个正方形，请输入它的边长：");
        Scanner input = new Scanner(System.in);
        a = input.nextInt();
        System.out.println("该正方形的面积=" + a * a + "\n");
    }
}

class ProtoTypeManager {
    private HashMap<String, Shape> ht = new HashMap<String, Shape>();

    public ProtoTypeManager() {
        ht.put("Circle", new Circle());
        ht.put("Square", new Square());
    }

    public void setShape(String key, Shape obj) {
        ht.put(key, obj);
    }

    public Shape getShape(String key) {
        Shape temp = ht.get(key);
        return (Shape) temp.clone();
    }
}

public class ProtoTypeShape {
    public static void main(String[] args) {
        ProtoTypeManager pm = new ProtoTypeManager();
        Shape obj1 = (Circle) pm.getShape("Circle");
        obj1.countArea();
        Shape obj2 = (Shape) pm.getShape("Square");
        obj2.countArea();
    }
}
